package com.bank.service.impl;

import com.bank.constant.MessageConstant;
import com.bank.dto.TransactionPageQueryDTO;
import com.bank.entity.BillTransaction;
import com.bank.exception.AccountNotFoundException;
import com.bank.mapper.AccountMapper;
import com.bank.mapper.BillTransactionMapper;
import com.bank.mapper.UserMapper;
import com.bank.result.PageResult;
import com.bank.service.BillTransactionService;
import com.bank.vo.AccountLoginVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BillTransactionServiceImpl implements BillTransactionService {
    @Autowired
    private BillTransactionMapper billTransactionMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AccountMapper accountMapper;

    @Override
    public PageResult pageQuery(TransactionPageQueryDTO queryDTO) {
        // 查询queryDTO accountId是否在下列账户中
        List<AccountLoginVO> accountLoginVOList = accountMapper.getAllAccountsByUserId(queryDTO.getUserId());
        if (accountLoginVOList.stream().noneMatch(account -> account.getAccountId().equals(queryDTO.getAccountId()))) {
            // 访问非法账户
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_ILLEGAL_ACCESS);
        }
        // 开始分页查询
        PageHelper.startPage(queryDTO.getPageNumber(), queryDTO.getPageSize());
        Page<BillTransaction> billTransactionPage = billTransactionMapper.pageQuery(queryDTO);

        long total = billTransactionPage.getTotal();
        List<BillTransaction> records = billTransactionPage.getResult();

        return new PageResult(total, records);
    }
}
